package com.kuangstudy.config.redis;
import io.rebloom.client.Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/6/10 10:42
 */
@Configuration
@Slf4j
public class RedisBloomConfiguration {

    // host地址
    @Value("${redis.bloom.host}")
    private String host;
    // 密码
    @Value("${redis.bloom.password}")
    private String password;
    // 端口
    @Value("${redis.bloom.port}")
    private Integer port;
    // 选择的数据库
    @Value("${redis.bloom.database}")
    private Integer database;
    // 超时时间
    @Value("${redis.bloom.time-out}")
    private Integer timeout;
    // 基数
    @Value("${redis.bloom.capacity}")
    private Integer capacity;
    // 错误率
    @Value("${redis.bloom.rate}")
    private Double rate;

    /**
     * 初始化jedis连接器对象
     * @return
     */
    @Bean
    public JedisPool jedisPool() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(8);
        poolConfig.setMaxTotal(8);
        poolConfig.setMaxWaitMillis(5 * 1000);
        JedisPool jedisPool = new JedisPool(poolConfig, host, port,
                timeout, password, database);
        return jedisPool;
    }


    /**
     * 用连接池创建bloomfilter的client客户端对象
     * @param pool
     * @return
     */
    @Bean
    public Client rebloomClient(JedisPool pool) {
        // 初始化bloomfilter的client对象
        Client client = new Client(pool);
        try {
            // 初始化bloomfilter的容错率 值越小速度越快，误判率越高
            client.createFilter("redis:bloom:filter", capacity, rate);
        } catch (Exception ex) {
            log.info("bloom过滤器已经存在，异常信息是：{}", ex.getMessage());
        }
        return client;
    }
}